//
//  UIImage+Extend.m
//  PAMobileWallet
//
//  Created by Gavin Zhang on 7/14/13.
//  Copyright (c) 2013 平安付. All rights reserved.
//

#import "UIImage+Extend.h"

@implementation UIImage (Extend)
- (UIImage *)pullImageWidthTo:(CGFloat)newWidth {
    if (self.size.width >= newWidth) {
        return self;
    }
    
    UIImage *newImage = nil;
    NSUInteger width = self.size.width;
    NSUInteger height = self.size.height;
    int rightOriginX = 0;
    int middleOriginX = 0;
    
    if (width%2 == 0) {
        rightOriginX = width/2;
        middleOriginX = width/2;
    }
    else {
        rightOriginX = width/2+2;
        middleOriginX = width/2+1;
    }
    
    CGImageRef imageRefLeft = CGImageCreateWithImageInRect([self CGImage], CGRectMake(0, 0, width/2, height));
    UIImage *imageLeft = [UIImage imageWithCGImage:imageRefLeft];
    CGImageRef imageRefMiddle = CGImageCreateWithImageInRect([self CGImage], CGRectMake(middleOriginX, 0, 1, height));
    UIImage *imageMiddle = [UIImage imageWithCGImage:imageRefMiddle];
    CGImageRef imageRefRight = CGImageCreateWithImageInRect([self CGImage], CGRectMake(rightOriginX, 0, width/2, height));
    UIImage *imageRight = [UIImage imageWithCGImage:imageRefRight];
    
    CGImageRelease(imageRefLeft);
    CGImageRelease(imageRefMiddle);
    CGImageRelease(imageRefRight);
    
    CGSize newSize = CGSizeMake(newWidth, height);
    int newCount = 0;
    
    if (width%2 == 0) {
        newCount = newSize.width - width;
    }
    else {
        newCount = newSize.width-width+1;
    }
    
    UIGraphicsBeginImageContext(newSize);
    
    [imageLeft drawInRect:CGRectMake(0, 0, imageLeft.size.width, imageLeft.size.height)];
    
    for (int i=0; i<newCount; i++) {
        [imageMiddle drawInRect:CGRectMake(imageLeft.size.width+i, 0, 1, height)];
    }
    
    [imageRight drawInRect:CGRectMake(imageLeft.size.width+newCount, 0, imageRight.size.width, imageRight.size.height)];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
	UIGraphicsEndImageContext();
    
    return newImage;
}
@end
